package logs

import (
	"context"
	"fmt"
	"github.com/cloudwego/hertz/pkg/app"
	"github.com/ezcloud/ezapp/pkg/core/log"
	"github.com/ezcloud/ezapp/pkg/core/strs"
	"github.com/ezcloud/ezapp/pkg/middleware/i18n"
	"strings"
	"time"
)

func AccessLogHandler() app.HandlerFunc {
	return func(c context.Context, ctx *app.RequestContext) {
		start := time.Now()
		ctx.Next(c)

		status := ctx.Response.StatusCode()
		path := strs.Bytes2String(ctx.Request.URI().PathOriginal())
		latency := time.Since(start)
		method := strs.Bytes2String(ctx.Request.Header.Method())
		clientIP := ctx.ClientIP()

		handlerPkgPath := strings.Split(ctx.HandlerName(), "/")
		handleName := ""
		if len(handlerPkgPath) > 0 {
			handleName = handlerPkgPath[len(handlerPkgPath)-1]
		}

		baseLog := fmt.Sprintf("| %s | %s | %d | %v | %s | %s | %v | %s | %s",
			string(ctx.GetRequest().Scheme()), ctx.Host(), status,
			latency, clientIP, method, path, handleName, i18n.GetLocale(c))

		log.CtxInfof(c, "%s ", baseLog)
	}
}
